﻿//Force setting jQuery support cross domain.
//This line mostly has effective in IE
jQuery.support.cors = true;

$(function () {

    $("#country_checkall").click(function () {
        $('.case').attr('checked', 'checked');
        setupLabel();
        $('.list_content_box').show();
        for (var i = 0; i < arrCountry.length; i++) {
            $("#countryItem" + arrCountry[i].Country.Id).remove();
        }
        for (var i = 0; i < arrCountry.length; i++) {
            addCountryItemDisplay(arrCountry[i], false);
        }
    });
    $("#country_clearall").click(function () {
        $('.case').removeAttr('checked');
        setupLabel();
        $('.list_content_box').hide();
        for (var i = 0; i < arrCountry.length; i++) {
            $("#countryItem" + arrCountry[i].Country.Id).remove();
        }
    });

    /*$(".txt_date").datepicker({
        showOn: "button",
        buttonImage: "images/btn_ca.png",
        buttonImageOnly: true
    });*/

    //$('.list_countries').jScrollPane({ animateScroll: true });
    $('.countries').hide();
    $('.btn_countries').click(function (event) {
        event.stopPropagation();
        if ($('#countries_list').css('display') == 'none') {
            $('#countries_list').show();
            $('#list_count_temp').css('display', 'none');
        } else {
            $('#countries_list').hide();
        }
        $(document).click(function () {
            if ($('#countries_list').css('display') != 'none') {
                $('#countries_list').hide();
            }
        });
        $('#countries_list').click(function (event) {
            event.stopPropagation();
        });
    });

    $('select.select_time').customStyle();
    $('.scroll-pane').jScrollPane({ animateScroll: true });
    $('.list_content_box').hide();
});

var arrMedia = new Array(); // contain all media object {Id:1,Name:'SMS'}
var arrCountry = new Array(); // contain all country object {Id:1 , CountryId:{Id:5,Name:'China'},LanguageId:[{Id:,Name}],TimezoneId:[{Id:,Name}],MediaSelected:[1,2]}

//Bind Country infomration for Country dialog
function getListCountry() {
    $("#list_count_temp").css("display", "none");

    $.getJSON(gb_servicePath+'/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        $.each(json1.ReturnData, function (i, val) {
                            // check if alredy add country in combobox
                            if ($("#country" + val.Country.Id).length == 0) {
                                var o = $("#list_count_temp").clone();
                                $(o).css("display", "block");
                                $(o).find("label").attr("id", "label_check_country" + val.Country.Id);
                                $(o).find("input").attr("value", val.Country.Name);
                                $(o).attr("id", "country" + val.Country.Id);
                                $(o).attr("value", val.Country.Id);
                                $(o).find("span").html(val.Country.Name);

                                $(".countries #list_countries").append(o);

                            }
                            var o = new Object();
                            o.Id = val.Id;
                            var country = new Object();
                            country.Id = val.Country.Id;
                            country.Name = val.Country.Name;
                            o.Country = country;
                            var timezone = new Object();
                            timezone.Id = val.Timezone.Id;
                            timezone.Name = val.Timezone.Name.split(")")[0] + ")";
                            timezone.Value = val.Timezone.Value;
                            o.Timezone = timezone;
                            var languages = new Array();
                            try {
                                var language = new Object();
                                language.Id = val.Language.Id;
                                language.Name = val.Language.Name;
                                language.selected = true;
                                language.CountryPreId = val.Id;
                                var medias = new Array();
                                for (var i = 0; i < arrMedia.length; i++) {
                                    var media = new Object();
                                    media.Id = arrMedia[i].Id;
                                    media.Name = arrMedia[i].Name;
                                    media.selected = true;
                                    medias.push(media);
                                }
                                language.Media = medias;
                                languages.push(language);
                            }
                            catch (e) {
                            }
                            o.Language = languages;
                            arrCountry.push(o);
                            // addCountryItemDisplay(o, false);
                        });
                        // $('.countries #list_countries').jScrollPane();

                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                            var parentid = $(this).parent().attr("id");
                            if (parentid.substring(0, 7) == "country") {
                                //click select/unselected in combo country
                                //alert("in country combo selected " + $(this).parent().attr("value"));
                                if ($(this).hasClass("c_on")) {
                                    //alert("add country " + $(this).parent().attr("value"));
                                    for (var i = 0; i < arrCountry.length; i++) {
                                        if (arrCountry[i].Country.Id == $(this).parent().attr("value")) {
                                            addCountryItemDisplay(arrCountry[i], false);
                                            // break;
                                        }
                                    }
                                } else {

                                    $("#countryItem" + $(this).parent().attr("value")).remove();
                                }
                            }

                        });
                    }
                });
}
//get all media to arrMedia
function getMediaList() {
    $.getJSON(gb_servicePath+'/media/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {

                        $.each(json1.ReturnData, function (i, val) {
                            var o = new Object();
                            o.Id = val.Id;
                            o.Name = val.Name;
                            arrMedia.push(o);
                        });
                        getListCountry();
                    }
                });
}
function addCountryItemDisplay(oCountry, isReplace) {
    //check if exist

    var iCountry;
    var needAppend = false;
    if ($("#countryItem" + oCountry.Country.Id).length > 0) {
        if (isReplace) { // if replace --> delete old instance , create new one
            $("#countryItem" + oCountry.Country.Id).remove();
            iCountry = $("<div class='list_content_box'><div class='left maxWidth'><h1></h1><select class='select_time' style='position: absolute; opacity: 0; font-size: 11px; height: 22px;' ></select><span class='select_time' style='display: inline-block; '><span class='customStyleSelectBoxInner' style='width: 67px; display: inline-block;'></span></span></div><div class='marginLft05 left'></div></div>");
            needAppend = true;
        } else {
            // get to iCountry
            iCountry = $("#countryItem" + oCountry.Country.Id);
        }
    } else {
        // if not exist --> create new one
        needAppend = true;
        iCountry = $("<div  class='list_content_box'><div class='left maxWidth'><h1></h1><select class='select_time' style='position: absolute; opacity: 0; font-size: 11px; height: 22px;'></select><span class='select_time cus_ddl' style='display: inline-block; '><span class='customStyleSelectBoxInner cus_ddl_mid' style='width: 67px; display: inline-block;'></span><span class='cus_ddl_right'></span></span></div><div class='marginLft05 left'></div></div>");

    }

    $(iCountry).attr("id", "countryItem" + oCountry.Country.Id);
    $(iCountry).attr("value", oCountry.Country.Id);
    $(iCountry).find("h1").html(oCountry.Country.Name);
    $(iCountry).css("display", "block");


    // bind timezone
    if ($("#optionTimezone" + oCountry.Country.Id + "_" + oCountry.Timezone.Id).length == 0) {
        var o = $("<option id='optionTimezone" + oCountry.Country.Id + "_" + oCountry.Timezone.Id + "' value='" + oCountry.Timezone.Id + "' >" + oCountry.Timezone.Name + "</option>");
        $(iCountry).find("select").append(o);
        if ($(iCountry).find("option").length == 1) {
            $(iCountry).find(".customStyleSelectBoxInner").html(oCountry.Timezone.Name);
        }
    }
    //bind languages
    try { // catch for none languges or media
        for (var j = 0; j < oCountry.Language.length; j++) {
            if ($("#language" + oCountry.Country.Id + "_" + oCountry.Language[j].Id).length == 0) {
                var o = $("<div id='language" + oCountry.Country.Id + "_" + oCountry.Language[j].Id + "' value='" + oCountry.Language[j].Id + "' class='list_lang'><label class='label_check languagesCheck' onclick='checkall(this);'><input type='checkbox'/>" + "<span>" + oCountry.Language[j].Name + "</span>" + "</label><div class='sub_lang'></div></div>");
                $(o).attr("CountryPreId", oCountry.Language[j].CountryPreId);
                $(iCountry).find(".marginLft05").append(o);
                if (oCountry.Language[j].selected == true) {
                    $(o).find(".label_check").addClass("c_on");
                    $(o).find("input").attr("checked", "checked");
                } else {
                    $(o).find(".label_check").removeClass("c_on");
                }
                //bind media
                var arrMedias = oCountry.Language[j].Media;
                for (var i = 0; i < arrMedias.length; i++) {
                    if ($("#media" + oCountry.Country.Id + "_" + oCountry.Language[j].Id + "_" + arrMedias[i].Id).length == 0) {
                        var oMedia = $("<label id='media" + oCountry.Country.Id + "_" + oCountry.Language[j].Id + "_" + arrMedias[i].Id + "' value='" + arrMedias[i].Id + "' class='label_check' onclick='checkparent(this);'><input  type='checkbox' class='chk_child'/>" + "<span>" + arrMedias[i].Name + "</span>" + "</label>");
                        if (arrMedias[i].selected == true) {
                            $(oMedia).addClass("c_on");
                            $(oMedia).find("input").attr("checked", "checked");
                        } else {
                            $(oMedia).removeClass("c_on");
                        }
                        $(o).find(".sub_lang").append(oMedia);
                    }
                }
            }
        }
    } catch (e) {
        alert(e);
    }

    // if (needAppend) {
    //$("#"+iCountry.attr("id")).remove();

    if ($("#country_select_list").find(".jspPane").length > 0) {
        $("#country_select_list").find(".jspPane").append(iCountry);
    } else {
        $("#country_select_list").append(iCountry);
    }
    //}
    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });
}
//function resizeCountriesBox() {
//    var docW = $(window).width();
//    if (docW > 1100) {
//        $("#box_select_countries").css("top", 129);
//        $("#box_select_countries").css("left", (docW - 1100) / 2 + 756);
//    } else {
//        $("#box_select_countries").css("top", 129);
//        $("#box_select_countries").css("left", 756);
//    }
//}
$(document).ready(function () {
    $("#box_select_countries").css("display", "none");
    $(window).resize(function () {
        //resizeCountriesBox();
    });
    //resizeCountriesBox();
    //getListCountry();
    getMediaList();
    $('body').addClass('has-js');
    /*$('.label_check, .label_radio, .label_check_ip').click(function () {
    setupLabel();
    });
    setupLabel();*/
    $('select.select_countries').customStyle();
    $('input.case').click(function () {
        var currentId = $(this).attr('id');
        if ($(this).is(':checked')) {
            $('#list_content_box' + currentId[8]).show();
        }
        else {
            $('#list_content_box' + currentId[8]).hide();
        }
    });

    /*parent.$('div.rows').each(function () {
    if (parent.$(this).is(":visible")) {
    var currentId = parent.$(this).attr('id');
    $('label#label_check' + currentId[4]).addClass('c_on');
    $('input#checkbox' + currentId[4]).attr('checked', 'checked');
    $('#list_content_box' + currentId[4]).show();
    }
    });*/
    $('#btCancel_select_country').click(function () {
        $("#box_select_countries").css("display", "none");
        $(".box_countries").find(".list_content_box").each(function () {
            $(this).remove();
        });
    });
    $('#btSave_select_country').click(function () {
        // Show the country box

        //get country info  
        arrCurrentCountry = new Array();
        $("#listCountries").find(".jspPane").find(".rows").each(function () {
            if ($(this).attr("id") != "country_temp") {
                $(this).remove();
            }
        });
        $("#box_select_countries").css("display", "none");
        $(".box_countries").find(".list_content_box").each(function () {
            var o = new Object();
            var country = new Object();
            country.Id = $(this).attr("value");
            country.Name = $(this).find("h1").html();
            o.Country = country;
            var timezone = new Object();
            $(this).find("option").each(function () {
                if ($(this).attr("selected") == true) {
                    timezone.Id = $(this).attr("value");
                    timezone.Name = $(this).html();
                }
            });
            o.Timezone = timezone;

            var languages = new Array();
            $(this).find(".list_lang").each(function () {
                var language = new Object();
                language.Id = $(this).attr("value");
                language.Name = $(this).find("span").html();
                language.CountryPreId = $(this).attr("CountryPreId");
                if ($(this).find(".languagesCheck").hasClass("c_on")) {
                    language.selected = true;
                } else {
                    language.selected = false;
                }
                var medias = new Array();
                $(this).find(".sub_lang").find(".label_check").each(function () {
                    var media = new Object();
                    media.Id = $(this).attr("value");
                    media.Name = $(this).find("span").html();
                    if ($(this).hasClass("c_on")) {
                        media.selected = true;
                    } else {
                        media.selected = false;
                    }
                    medias.push(media);
                })
                language.Media = medias;
                languages.push(language);
            })
            o.Language = languages;
            //  arrCurrentCountry.push(o);
            // alert(JSON.stringify(o));
            addCountryPre(o);
            $(this).remove();
        });

        refreshScrollbarListCountry();

        //addCountryPre(arrCountry[0]);
        //parent.$("#listCountries").css("display", "block");

        sortCountryTable(false);
    });


});


function checkall(str) {
    if ($(str).find('input').is(':checked')) {
        $(str).next().find('.chk_child').attr('checked', 'checked');
    }
    else {

        $(str).next().find('.chk_child').removeAttr('checked');
    }
    setupLabel();

}
function checkparent(str) {
    if ($(str).find('input').is(':checked')) {
        $(str).parent().prev().find('input').attr('checked', 'checked');
    }
    else {
        var flg = false;
        $(str).parent().find('input').each(function () {
            if ($(this).is(':checked')) {
                flg = true;
            }
        });
        if (flg) {
            $(str).parent().prev().find('input').attr('checked', 'checked');
        }
        else {
            $(str).parent().prev().find('input').removeAttr('checked');
        }
    }
}